package com.atguigu.gulimall.auth.controller;

import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.ThridPartFeignService;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.atguigu.common.constant.AuthServerConstant.SMS_CODE_CACHE_PREFIX;
import static com.atguigu.common.exception.BizCodeEnume.SMS_CODE_EXCEPTION;

@Controller
public class LoginController {
    /**
     * 发送一个请求直接跳转到一个页面
     * SpringMVC viewController
     * 讲请求和页面映射过来
     * GulimallWebConfig的addViewControllers
     */
    /*
    @GetMapping("/login.html")
    public String loginPage(){
        return "login";
    }

    @GetMapping("/reg.html")
    public String regPage(){
        return "reg";
    }
     */
    @Autowired
    ThridPartFeignService thridPartFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {
        String redisCode = redisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + phone);
        if(!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(SMS_CODE_EXCEPTION.getCode(), SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 5);
        String substring = code + "_" + System.currentTimeMillis();
        thridPartFeignService.sendCode(phone, code);
        //redis缓存，防止同一个phone在60秒内重复发送验证码
        redisTemplate.opsForValue().set(
                SMS_CODE_CACHE_PREFIX + phone,
                substring,
                900,
                TimeUnit.SECONDS
        );
        return R.ok();
    }

    /**
     * redirectAttributes模拟重定向携带数据 涉及到分布式session问题
     * TODO session
     * @param vo
     * @param result
     * @param redirectAttributes
     * @return
     */
    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes,
                         HttpSession session){
        if(result.hasErrors()){
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(
                    FieldError::getField
                    , FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors", errors);

            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //注册，调用远程服务
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if(!StringUtils.isEmpty(s)){
            if(code.equals(s.split("_")[0])){
                //删除验证码
                redisTemplate.delete(SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //远程调用
            }else{
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
//            model.addAttribute("errors",errors);
                redirectAttributes.addFlashAttribute("errors", errors);

                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors", errors);

            return "redirect:http://auth.gulimall.com/reg.html";
        }

        //注册成功跳转登录
        return "redirect:/login.html";
    }
}
